package com.wuyan.wupicturebackend.manager.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.json.JSONUtil;
import com.wuyan.wupicturebackend.exception.BusinessException;
import com.wuyan.wupicturebackend.exception.ErrorCode;
import com.wuyan.wupicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.wuyan.wupicturebackend.model.entity.Picture;
import com.wuyan.wupicturebackend.model.entity.Space;
import com.wuyan.wupicturebackend.model.entity.SpaceUser;
import com.wuyan.wupicturebackend.model.entity.User;
import com.wuyan.wupicturebackend.model.enums.SpaceRoleEnum;
import com.wuyan.wupicturebackend.model.enums.SpaceTypeEnum;
import com.wuyan.wupicturebackend.service.PictureService;
import com.wuyan.wupicturebackend.service.SpaceService;
import com.wuyan.wupicturebackend.service.SpaceUserService;
import com.wuyan.wupicturebackend.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.wuyan.wupicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 自定义权限接口实现类
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    //默认是/api
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    private SpaceUserService spaceUserService;
    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    /**
     * 返回一个账号所有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        //判断loginType，仅对类型为“space”进行权限校验
        if(!StpKit.SPACE_TYPE.equals(loginType)){
            return new ArrayList<>();
        }
        //管理员权限，表示权限校验通过
        List<String> ADMIN_PERMISSIONS = spaceUserAuthManager.getPermissionsByRole(SpaceRoleEnum.ADMIN.getValue());
        //获取上下文对象
        SpaceUserAuthContext authContext = getAuthContextByRequest();
        //如果所有字段都为空，表示查询公共图库，可以通过
        if(isAllFieldsNull(authContext)){
            return ADMIN_PERMISSIONS;
        }
        //获取userId
        User loginUser = (User) StpKit.SPACE.getSessionByLoginId(loginId).get(USER_LOGIN_STATE);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"用户未登录");
        }
        Long userId = loginUser.getId();
        //优先从上下文中获取SpaceUser对象
        SpaceUser spaceUser = authContext.getSpaceUser();
        if(spaceUser != null){
           return spaceUserAuthManager.getPermissionsByRole(spaceUser.getSpaceRole());
        }
        //如果有spaceUserId，必然是团队空间，通过数据库查询SpaceUser对象
        Long spaceUserId = authContext.getSpaceUserId();
        if(spaceUserId!=null){
            spaceUser = spaceUserService.getById(spaceUserId);
            if(spaceUser == null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到空间用户信息");
            }
            //取出当前登录用户对应的spaceUser
            SpaceUser loginSpaceUser = spaceUserService.lambdaQuery()
                    .eq(SpaceUser::getSpaceId, spaceUser.getSpaceId())
                    .eq(SpaceUser::getUserId, userId)
                    .one();
            if(loginSpaceUser == null){
                return new ArrayList<>();
            }
            //这里会导致管理员再私有空间没有权限，可以再查一个库处理
            return spaceUserAuthManager.getPermissionsByRole(loginSpaceUser.getSpaceRole());
        }
        //如果没有spaceUserId，尝试通过spaceId或pictureId获取Space对象并处理
        Long spaceId = authContext.getSpaceId();
        if(spaceId == null){
            //如果没有spaceId，通过pictureId获取picture对象和space对象
            Long pictureId = authContext.getPictureId();
            //图片id也没有，则默认通过权限校验
            if(pictureId == null){
                return ADMIN_PERMISSIONS;
            }
            Picture picture = pictureService.lambdaQuery()
                    .eq(Picture::getId, pictureId)
                    .select(Picture::getId, Picture::getSpaceId, Picture::getSpaceId, Picture::getUserId)
                    .one();
            if(picture == null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到图片信息");
            }
            spaceId = picture.getSpaceId();
            //公共图库，仅本人或管理员可操作
            if(spaceId == null){
                if(picture.getUserId().equals(userId) || userService.isAdmin(loginUser)){
                    return ADMIN_PERMISSIONS;
                }else{
                    //不是自己的图片，仅可查看
                    return Collections.singletonList(SpaceUserPermissionConstant.PICTURE_VIEW);
                }
            }
        }

        //获取Space对象
        Space space = spaceService.getById(spaceId);
        if(space == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到空间信息");
        }
        //根据Space类型判断权限
        if(space.getSpaceType() == SpaceTypeEnum.PRIVATE.getValue()) {
            //私有空间，仅本人或管理员有权限
            if (space.getUserId().equals(userId) || userService.isAdmin(loginUser)) {
                return ADMIN_PERMISSIONS;
            } else {
                return new ArrayList<>();
            }
        } else{
            //团队空间
            spaceUser = spaceUserService.lambdaQuery()
                    .eq(SpaceUser::getSpaceId, spaceId)
                    .eq(SpaceUser::getUserId, userId)
                    .one();
            if(spaceUser == null){
                return new ArrayList<>();
            }
            return spaceUserAuthManager.getPermissionsByRole(spaceUser.getSpaceRole());
        }
    }

    /**
     * 暂时不使用
     */
    @Override
    public List<String> getRoleList(Object o, String s) {
        return new ArrayList<>();
    }
    /**
     * 从请求中获取上下文对象
     */
    public SpaceUserAuthContext getAuthContextByRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String contentType = request.getHeader(Header.CONTENT_TYPE.getValue());
        SpaceUserAuthContext authRequest;
        //获取请求参数
        if(ContentType.JSON.getValue().equals(contentType)){
            String body = ServletUtil.getBody(request);
            authRequest = JSONUtil.toBean(body, SpaceUserAuthContext.class);
        }else{
            Map<String, String> paramMap = ServletUtil.getParamMap(request);
            authRequest = BeanUtil.toBean(paramMap, SpaceUserAuthContext.class);
        }
        //根据请求路径区分id字段的含义
        Long id = authRequest.getId();
        if(ObjUtil.isNotNull(id)){
            //获取到请求路径的业务前缀 /api/picture/aaa?a=1
            String requestURL = request.getRequestURI();
            //先替换掉上下文，剩下的就是前缀
            String partURI = requestURL.replace(contextPath + "/", "");
            //获取前缀的第一个斜杠前的字符串
            String moduleName = StrUtil.subBefore(partURI, "/", false);
            switch (moduleName) {
                case "picture":
                    authRequest.setPictureId(id);
                    break;
                case "spaceUser":
                    authRequest.setSpaceUserId(id);
                    break;
                case "space":
                    authRequest.setSpaceId(id);
                    break;
                default:
            }
        }
        return authRequest;
    }

    private boolean isAllFieldsNull(Object object) {
        if (object == null) {
            return true; // 对象本身为空
        }
        // 获取所有字段并判断是否所有字段都为空
        return Arrays.stream(ReflectUtil.getFields(object.getClass()))
                // 获取字段值
                .map(field -> ReflectUtil.getFieldValue(object, field))
                // 检查是否所有字段都为空
                .allMatch(ObjectUtil::isEmpty);
    }

}
